package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.MessageModel;
import com.zrwl.poscloud.base.entity.MessageWx;
import com.zrwl.poscloud.base.entity.User;
import com.zrwl.poscloud.base.entity.UserWx;
import com.zrwl.poscloud.base.enums.EMessageModelType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.DateUtils;
import com.zrwl.poscloud.commons.utils.HttpRequestUtil;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.MessageWxMapper;
import com.zrwl.poscloud.xo.service.MessageModelService;
import com.zrwl.poscloud.xo.service.MessageWxService;
import com.zrwl.poscloud.xo.service.UserService;
import com.zrwl.poscloud.xo.service.UserWxService;
import com.zrwl.poscloud.xo.vo.MessageWxVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信消息 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-12-30
 */
@Service
public class MessageWxServiceImpl extends SuperServiceImpl<MessageWxMapper, MessageWx> implements MessageWxService {

    @Autowired
    private MessageWxService messageWxService;
    @Resource
    private MessageWxMapper messageWxMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserWxService userWxService;
    @Autowired
    private MessageModelService messageModelService;

    public static String sendTemplateMessage = "http://localhost:7603/wx/sendWeChatMessage";

    @Override
    public IPage<MessageWxVO> getPageList(MessageWxVO messageWxVO) {
        Page<MessageWxVO> page = new Page<>();
        page.setCurrent(messageWxVO.getCurrentPage());
        page.setSize(messageWxVO.getPageSize());
        IPage<MessageWxVO> pageList = messageWxMapper.getPageList(page, messageWxVO);
        List<MessageWxVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<MessageWx> getAllList(MessageWxVO messageWxVO) {
        QueryWrapper<MessageWx> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<MessageWx> list = messageWxService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(MessageWxVO messageWxVO) {
        if(messageWxVO.getOpenId() == null){
            User user = userService.getById(messageWxVO.getToUid());
            UserWx userWx = userWxService.getByUserId(user.getUid());
            messageWxVO.setModelType(2);
            messageWxVO.setOpenId(userWx.getOpenId());
        }
        MessageWx entity = new MessageWx();
        BeanUtils.copyProperties(messageWxVO, entity, SysConf.STATUS);
        entity.insert();
        messageWxVO.setUid(entity.getUid());
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String add(MessageWxVO messageWxVO,EMessageModelType eMessageModelType) {
        int type = eMessageModelType.getType();
        MessageModel templateMessage = messageModelService.getTemplateMessage(EMessageModelType.WX, type % 10);
        messageWxVO.setTemplateId(templateMessage.getCode());
        return add(messageWxVO);
    }

    @Override
    public String addSend(MessageWxVO messageWxVO) {
        add(messageWxVO);
        String sendAMessage = sendMessage(messageWxVO);
        JSONObject result = JSONObject.parseObject(sendAMessage);
        switch (result.getString("errcode")) {
            case "0":
                return ResultUtil.successWithMessage("发送成功");
        }
        return ResultUtil.errorWithMessage("发送失败,已存入微信消息中");
    }
    @Override
    public String edit(MessageWxVO messageWxVO) {
        MessageWx entity = messageWxService.getById(messageWxVO.getUid());
        BeanUtils.copyProperties(messageWxVO, entity);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(MessageWxVO messageWxVO) {
        MessageWx entity = messageWxService.getById(messageWxVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String sendMessage(MessageWxVO messageWxVO){
        MessageWx entity = messageWxService.getById(messageWxVO.getUid());
        String sendStr = "openId=" + entity.getOpenId()
                + "&" + "templateId=" + entity.getTemplateId()
                + "&" + "url=" + entity.getUrl()
                + "&" + "first=" + entity.getFirst()
                + "&" + "remark=" + entity.getRemark()
                + "&" + "content=" + entity.getContent();
       Map<String,String> backStr = HttpRequestUtil.sendPost2(sendTemplateMessage, sendStr);
        if(HttpRequestUtil.checkState(backStr)){
            throw new RuntimeException("暂时无法连接，可能是由于系统出现故障，请联系管理员人工处理！");
        }
        //更新发送状态
        JSONObject result = JSONObject.parseObject(backStr.get("result"));
        switch (result.getString("errcode")) {
            case "0":
                entity.setSendTime(new Date());
                entity.setStatus(2);
                //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
                entity.updateById();
                break;
        }
        return backStr.get("result");
    }

    @Override
    public String resendMessage(MessageWxVO messageWxVO) {
        MessageWx entity = messageWxService.getById(messageWxVO.getUid());
        entity.setStatus(1);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return messageWxService.sendMessage(messageWxVO);
    }

    @Override
    public void balanceAndRemainingReminders() {

        QueryWrapper<MessageWx> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        queryWrapper.eq("template_id","dqiXhja4Uia8GGKKhX1urBVyoOvANH0Ak8_T6fgkehk").or()
                .eq("template_id","dqiXhja4Uia8GGKKhX1urBVyoOvANH0Ak8_T6fgkehk2");
        queryWrapper.ge("create_time",DateUtils.getYestodayStartTime());
        queryWrapper.le("create_time",DateUtils.getYestodayEndTime());
        List<MessageWx> list = messageWxService.list(queryWrapper);
        for (MessageWx messageWx : list) {
            MessageWxVO messageWxVO = new MessageWxVO();
            messageWxVO.setUid(messageWx.getUid());
            messageWxService.sendMessage(messageWxVO);
        }
    }
}
